package cn.com.tianpeidong.restaurantadmin.project.admin.user.service.impl;

import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.com.tianpeidong.restaurantadmin.common.constant.Constants;
import cn.com.tianpeidong.restaurantadmin.common.exception.user.UserBlockedException;
import cn.com.tianpeidong.restaurantadmin.common.exception.user.UserDeleteException;
import cn.com.tianpeidong.restaurantadmin.common.exception.user.UserNotExistsException;
import cn.com.tianpeidong.restaurantadmin.common.exception.user.UserPasswordNotMatchException;
import cn.com.tianpeidong.restaurantadmin.common.exception.user.UserPasswordRetryLimitExceedException;
import cn.com.tianpeidong.restaurantadmin.common.util.date.DateUtils;
import cn.com.tianpeidong.restaurantadmin.common.util.msg.MessageUtils;
import cn.com.tianpeidong.restaurantadmin.core.manager.AsyncManager;
import cn.com.tianpeidong.restaurantadmin.core.manager.factory.AsyncFactory;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.constant.UserStatus;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.entity.UserInfo;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.mapper.UserInfoMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.service.IAuthService;
import lombok.NonNull;

@Service
public class AuthServiceImpl implements IAuthService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo getUser(@NonNull String username, @NonNull String password) {

        // 查询用户信息
        UserInfo user = userInfoMapper.selectUserByLoginName(username);

        if (user == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists")));
            throw new UserNotExistsException();
        }
        
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.delete")));
            throw new UserDeleteException();
        }
        
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked", user.getRemark())));
            throw new UserBlockedException();
        }

        validate(user, password);

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(user);
        return user;
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(UserInfo user)
    {
        user.setUpdatedTime(DateUtils.getNowDate());
        userInfoMapper.updateUserInfo(user);
    }

    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;

    @PostConstruct
    public void init()
    {
        loginRecordCache = cacheManager.getCache("users");
    }

    public void validate(UserInfo user, String password)
    {
        String loginName = user.getUserName();

        AtomicInteger retryCount = loginRecordCache.get(loginName);

        if (retryCount == null)
        {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue())
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount)));
            throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue());
        }

        if (!matches(user, password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount)));
            loginRecordCache.put(loginName, retryCount);
            throw new UserPasswordNotMatchException();
        }
        else
        {
            clearLoginRecordCache(loginName);
        }
    }

    public boolean matches(UserInfo user, String newPassword)
    {
        return user.getPassword().equals(encryptPassword(user.getUserName(), newPassword, user.getSalt()));
    }

    public void clearLoginRecordCache(String username)
    {
        loginRecordCache.remove(username);
    }

    public String encryptPassword(String username, String password, String salt)
    {
        String md5 = new Md5Hash(username + password + salt).toHex().toString();
        return md5;
    }

}